package com.gingko.duominuo.utils
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.Observer
import com.gingko.duominuo.ui.fragment.PermissionFragment


class LDPermission private constructor() {
    private lateinit var mFragment: PermissionFragment

    companion object {
        private const val TAG: String = "PermissionHelper"
        const val REQUEST_CODE: Int = 0x11

        fun from(activity: AppCompatActivity): LDPermission = INSTANCE.apply {
            getPermissionsFragment(activity.supportFragmentManager)
        }

        fun from(fragment: Fragment): LDPermission = INSTANCE.apply {
            getPermissionsFragment(fragment.childFragmentManager)
        }

        //线程安全的单例
        private val INSTANCE: LDPermission by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            LDPermission()
        }
    }


    private fun getPermissionsFragment(fragmentManager: FragmentManager): PermissionFragment {
        return with(findRxPermissionsFragment(fragmentManager)) {
            if (this == null) {
                mFragment = PermissionFragment.newInstance()
                fragmentManager
                    .beginTransaction()
                    .add(mFragment, TAG)
                    .commitNow()
            } else {
                mFragment = this
            }
            mFragment
        }
    }

    private fun findRxPermissionsFragment(fragmentManager: FragmentManager): PermissionFragment? {
        return fragmentManager.findFragmentByTag(TAG) as PermissionFragment?
    }

    fun requestEach(
        vararg permissions: String,
        onRequestPermissionsResult: (permission: String, isGranted: Boolean) -> Unit
    ) {
        PermissionUtils.validatePermissions(permissions)

        //筛选出未授权的权限
        val permissionList =
            permissions.filter { permission -> !PermissionUtils.isGranted(mFragment.requireContext(), permission) }
        if (permissionList.isNotEmpty()) {//申请的权限列表不为空
            mFragment.refusedPermissionLiveData.observe(mFragment, Observer { refusedPermissions ->
                if (refusedPermissions.isEmpty()) {
                    permissions.forEach { onRequestPermissionsResult(it, true) }
                } else {
                    permissions.forEach {
                        onRequestPermissionsResult(it, !refusedPermissions.contains(it))
                    }
                }
            })
        } else {
            permissions.forEach { onRequestPermissionsResult(it, true) }
        }
        //请求权限
        mFragment.requestPermissions(
            permissionList.toTypedArray(),
            REQUEST_CODE
        )
    }


    fun request(
        vararg permissions: String,
        onRequestPermissionsResult: (isGranted: Boolean) -> Unit
    ) {
        PermissionUtils.validatePermissions(permissions)
        //筛选出未授权的权限
        val permissionList =
            permissions.filter { permission -> !PermissionUtils.isGranted(mFragment.requireContext(), permission) }
        if (permissionList.isNotEmpty()) {//申请的权限列表不为空
            mFragment.refusedPermissionLiveData.observe(mFragment, Observer { refusedPermissions ->
                onRequestPermissionsResult(refusedPermissions.isEmpty())
            })
            //请求权限
            mFragment.requestPermissions(
                permissionList.toTypedArray(),
                REQUEST_CODE
            )
        } else {
            onRequestPermissionsResult(true)
        }

    }

}